import { resolve } from 'node:path'
// import { fileURLToPath, URL } from 'node:url'
import Uni from '@uni-helper/plugin-uni'
import { WotResolver } from '@uni-helper/vite-plugin-uni-components/resolvers'
import UniHelperComponents from '@uni-helper/vite-plugin-uni-components'
import UniLayouts from '@uni-helper/vite-plugin-uni-layouts'
import UniPages from '@uni-helper/vite-plugin-uni-pages'
// import UniKuRoot from '@uni-ku/root'
import AutoImport from 'unplugin-auto-import/vite'

import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig(async () => {
  /**
   * 为兼容 @dcloudio/vite-plugin-uni 采用 CJS ，而 UnoCSS 只支持 ESM
   * @see https://github.com/dcloudio/uni-app/issues/4815
   */
  const UnoCSS = (await import('unocss/vite')).default

  return {
    resolve: {
      alias: {
        // '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@': resolve(__dirname, 'src'),
      },
    },
    plugins: [
      /**
       * vite-plugin-uni-pages
       * @see https://github.com/uni-helper/vite-plugin-uni-pages
       */
      UniPages({
        dts: 'src/typings/uni-pages.d.ts',
        subPackages: [
          'src/pages-sub',
        ],
        /**
         * 排除的页面，相对于 dir 和 subPackages
         * @default []
         */
        exclude: ['**/components/**/*.*'],
      }),

      /**
       * vite-plugin-uni-layouts
       * @see https://github.com/uni-helper/vite-plugin-uni-layouts
       */
      UniLayouts(),

      /**
       * unplugin-vue-components 按需引入组件
       * 注意：需注册至 uni 之前，否则不会生效
       * @see https://github.com/antfu/vite-plugin-components
       */
      UniHelperComponents({
        dts: 'src/typings/components.d.ts',
        // 'src/uni_modules/**',
        dirs: ['src/components/**'],
        resolvers: [WotResolver()],
        directoryAsNamespace: true,
      }),
      // UniKuRoot(),
      /**
       * unocss
       * @see https://github.com/antfu/unocss
       * see unocss.config.ts for config
       */

      Uni(),
      /**
       * unplugin-auto-import 按需 import
       * @see https://github.com/antfu/unplugin-auto-import
       */
      AutoImport({
        imports: ['vue', 'pinia', 'uni-app', {
          from: 'uni-mini-router',
          imports: ['createRouter', 'useRouter', 'useRoute'],
        },
          {
          from: 'wot-design-uni',
          imports: ['useToast', 'useMessage', 'useNotify', 'CommonUtil'],
        }],
        dts: 'src/typings/auto-imports.d.ts',
        dirs: [
          './src/composables','./src/hooks','./src/stores','./src/router',
        ],
        vueTemplate: true,
      }),
      UnoCSS(),
    ],

    /**
     * Vitest
     * @see https://github.com/vitest-dev/vitest
     */
    test: {
      environment: 'jsdom',
    },
  }
})
